<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>取消请求</title>
</head>

<body>
  <button>发送请求</button>
  <button>取消请求</button>
  <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.27.2/axios.min.js"></script>
  <script>
    let cancelFn
    let btns = document.querySelectorAll('button')
    btns[0].onclick = async () => {
      try{
        let result = await axios({
        url:'http://127.0.0.1:8090/delay-server',
        cancelToken:new axios.CancelToken((cancel)=>{
          cancelFn = cancel
        })
      })
      alert(result.data)
      }catch(error){
        if(axios.isCancel(error)){
          alert('请求被取消了')
        }else{
          alert(error.message)
        }
      }
    }
    btns[1].onclick = () => {
      if(cancelFn){
        cancelFn()
      }
    }

  </script>
</body>

</html>